package com.sddongyun.filter;

import com.alibaba.fastjson.JSONObject;
import com.sddongyun.common.RequestWrapper;
import com.sddongyun.common.ResponseWrapper;
import com.sddongyun.common.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求医保时 取出 参数
 * @author 01
 * @program wrapper-demo
 * @description 替换HttpServletRequest
 * @create 2018-12-24 21:04
 * @since 1.0
 **/
@Slf4j
public class ReplaceStreamFilter implements Filter {
    @Autowired
    JdbcTemplate jdbcTemplate;
    private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReplaceStreamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("StreamFilter初始化...");
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("ReplaceStreamFilter----"+((HttpServletRequest) request).getRequestURI());

        RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
        ResponseWrapper respWrapper = new ResponseWrapper((HttpServletResponse) response);

        String jsonParam = requestWrapper.getBodyString();
        logger.info("filter中打印request： "+ jsonParam);

        JSONObject endJson = new JSONObject();
        endJson.put("uri",((HttpServletRequest) request).getRequestURI());
        endJson.put("method",((HttpServletRequest) request).getMethod());
        endJson.put("bodyParams",requestWrapper.getBodyString());
        endJson.put("reqDate",formatDate(new Date()));

        chain.doFilter(requestWrapper, respWrapper);

        //获取返回值
        byte[] content = respWrapper.getContent();
        String realRes = new String(content, "UTF-8");
        logger.info("filter中打印response： " + realRes);

        //判断是否有值
        if (content.length > 0) {
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
        }else {
            realRes = "<out:business>ORA-错误:医保未返回</out:business>";
            ServletOutputStream out = response.getOutputStream();
            out.write(realRes.getBytes("Utf-8"));
            out.flush();
        }
        endJson.put("resStr", realRes);
        endJson.put("resDate", formatDate(new Date()));

        jdbcTemplate.update(
                "insert into ybserverlog(url,reqstr,reqtime,resstr,restime) VALUES (?,?,?,?,?)"
                ,endJson.get("uri").toString()
                ,endJson.get("bodyParams").toString()
                ,endJson.get("reqDate").toString()
                ,endJson.get("resStr").toString()
                ,endJson.get("resDate").toString()
        );

    }
 
    @Override
    public void destroy() {
        log.info("StreamFilter销毁...");
    }

    public String formatDate(Date date){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
}
